﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace Mbs.Net
{
    public static class SocketExtensions
    {
        internal static void SafeClose(this Socket socket)
        {
            try
            {
                if (socket != null && socket.Connected)
                    socket.Shutdown(SocketShutdown.Both);
            }
            catch
            {
            }

            try
            {
                if (socket != null && socket.Connected)
                    socket.Close();
            }
            catch
            {
            }
        }

        public static void InvokeAsyncMethod(this Socket socket, Func<SocketAsyncEventArgs, bool> method, EventHandler<SocketAsyncEventArgs> callback, SocketAsyncEventArgs args, Action<Exception> errorCallback)
        {
            try
            {
                if (!method(args))
                    callback(socket, args);
            }
            catch (Exception ex)
            {
                if (errorCallback != null)
                    errorCallback(ex);
                SafeClose(socket);
            }
        }

        public static bool IsLocalAddress(this IPAddress address)
        {
            return address.ToString() == "127.0.0.1";
        }
    }
}
